package com.hok.misc.file.separate;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Random;

import sun.misc.BASE64Encoder;


public class FileSeparation {
	private static final int FILE_PIECE_SIZE = 1024 * 100;
	
	public static BufferedReader getReader(File source, String charSet) throws IOException {
		InputStream is = new FileInputStream(source);
		UnicodeReader isr = new UnicodeReader(is, charSet);
		return new BufferedReader(isr);
	}
	
	public static File convert2Base64File(String path) throws IOException{
		InputStream is = new FileInputStream(path);
		BASE64Encoder b64=new BASE64Encoder();
		Random rd=new Random();
		File file=new File(System.getProperty("user.dir")+File.separator+rd.nextInt(99999));
		OutputStream bos=new Base64FilterOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		b64.encodeBuffer(is, bos);
		bos.flush();
		bos.close();
		is.close();
		return file;
	}
	
	public static void separate(String path) throws IOException {
		File file = convert2Base64File(path);
		long size = file.length();
		long lastPieceSize = size % FILE_PIECE_SIZE;
		long count = size / FILE_PIECE_SIZE;
		if (lastPieceSize > 0) {
			count += 1;
		} else {
			lastPieceSize = FILE_PIECE_SIZE;
		}
		
		Reader reader = getReader(file, "US-ASCII");
		
		char[] b = new char[FILE_PIECE_SIZE];
		for (int i = 0; i < count; i++) {
			int len = reader.read(b);
			String content = new String(b, 0, len);
			System.out.println(content);
		}
	}
	
	public static void main(String[] args) {
		try {
			separate("");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
